package com.bckj.freshnow.payment.service;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import com.bckj.freshnow.common.constant.PaymentConstants;
import com.bckj.freshnow.payment.model.PayResult;
import com.bckj.freshnow.payment.model.WxpayResultRequest;
import com.bckj.freshnow.payment.pay.wxpay.WxpayNotificationParseManager;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class PaymentResultService {
    public Object wxpayResult(WxpayResultRequest request) {
        NotificationParser parser = WxpayNotificationParseManager.getParser(request.getOutMerchantId());
        Assert.notNull(parser, "wechat pay parser is null");
        Transaction transaction;
        try {
            transaction = parser.parse(
                    new RequestParam.Builder()
                            .body(request.getBody())
                            .serialNumber(request.getSerialNumber())
                            .signature(request.getSignature())
                            .nonce(request.getNonce())
                            .timestamp(request.getTimestamp())
                            .build(),
                    Transaction.class
            );
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return MapUtil.builder().put("code", "FAIL").put("message", e.getMessage()).build();
        }
        PayResult payResult = toPayResult(transaction);
//        payResultMsgProducer.afterSend(
//                PayResultMsg.create()
//                        .setPayResult(payResult)
//        );
        return null;
    }

    private PayResult toPayResult(Transaction transaction) {
        PayResult result = new PayResult();
        result.setOutTradeNo(transaction.getOutTradeNo());
        result.setStatus(transaction.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS) ? PaymentConstants.PAY_STATUS_PAY_SUCCESS : PaymentConstants.PAY_STATUS_PAY_FAIL);
        return result;
    }
}
